package com.example.controller;

import com.example.mapper.UserMapper;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.service.impl.JwtUtil;
import com.example.utils.Md5Util;
import com.example.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")/*指定请求的映射路径*/
@Validated
public class UserController {
    // 手机号正则表达式（静态常量，复用正则对象提高效率）
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/register")
    public Result register(@jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$") String username,
                           @jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$")String password,
                           @jakarta.validation.constraints.Pattern(regexp = "^1[3-9]\\d{9}$") String userphone) {
        //查询用户
        User u = userService.findByUserName(username);
        if (u == null) {
            //没有占用
            userService.register(username, password, userphone);
            return Result.success("注册成功");
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<Result.ResponseData<Object>> login(@jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$") String username,
                                                     @jakarta.validation.constraints.Pattern(regexp = "^\\S{5,16}$")String password){
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        //判断该用户是否存在
        if(loginUser==null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确 loginUser对象中的password是否是密文
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //登录成功
            Map<String,Object> claims=new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token ="Bear "+ JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<Result.ResponseData<User>> userInfo(/*@RequestHeader(name="Authorization") String token*/){
        //根据用户查询名查询用户
        /*Map<String, Object> map = JwtUtil.parseToken(token);//用户业务参数集合maop
        String username = (String) map.get("username");*/
        Map<String,Object> map=ThreadLocalUtil.get();//获取在拦截器类中存储数据
        String username = (String) map.get("username");//获取存储数据
        User user = userService.findByUserName(username);

        return Result.success(user);
    }
/*    @PutMapping("/update")
    public Result uopdate(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }*/

    /*@PatchMapping("update")
    public Result update(@RequestParam @URL String avatarUrl){
        userService.update(avatarUrl);
        return Result.success();
    }*/

    //用户基本信息更新
    @PutMapping("/update")
    public Result update(
            // 手动接收普通字段（与 Postman 参数名严格一致）
            @RequestParam("id") Integer id,
            @RequestParam("userName") String userName,
            @RequestParam("nickName") @jakarta.validation.constraints.Pattern(regexp = "^\\S{1,10}$") String nickName,
            @RequestParam("userPhone") @jakarta.validation.constraints.Pattern(regexp = "^1[3-9]\\d{9}$") String userPhone,
            @RequestParam("email") @Email String email,
            // 单独接收文件字段
            @RequestPart(value = "userPic", required = false) MultipartFile userPic) {

        try {
            // 手动封装 User 对象
            User user = new User();
            user.setId(id);
            user.setUsername(userName);   // 实体类字段 username 对应前端 userName
            user.setNickname(nickName);   // 实体类字段 nickname 对应前端 nickName
            user.setUserphone(userPhone); // 实体类字段 userphone 对应前端 userPhone
            user.setEmail(email);

            // 处理头像文件（逻辑不变）
            if (userPic != null && !userPic.isEmpty()) {
                String originalFilename = userPic.getOriginalFilename();
                if (!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png")) {
                    return Result.error("头像仅支持jpg/png格式");
                }
                if (userPic.getSize() > 5 * 1024 * 1024) {
                    return Result.error("头像大小不能超过5MB");
                }
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + suffix;
                String savePath = "D:\\photo" + fileName;
                userPic.transferTo(new java.io.File(savePath));
                user.setUserpic("D:\\photo" + fileName);
            }

            userService.update(user);
            return Result.success("用户信息更新成功");

        } catch (IOException e) {
            return Result.error("头像上传失败：" + e.getMessage());
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String>params){
        //1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        //检验参数
        if(!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)
        ||!StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        //校验原密码是否正确
        //调用userService
        Map<String,Object>map=ThreadLocalUtil.get();
        String username=(String)map.get("username");
        User loginUser = userService.findByUserName(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码填写不正确");
        }
        //newPwd和rePwd是否一样
        if(!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一样");
        }
        //2.调用service完成密码更新
        userService.updatePwd(newPwd);
        return Result.success();
    }
}